﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;

namespace PrintExcel
{
    internal class IniFile
    {       

        #region 读取INI文件
        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="Section">段落</param>
        /// <param name="IniKey">关键字</param>
        /// <returns></returns>
        public static string GetFieldValue(string Section, string IniKey,string iniFileName)
        {                       
            StringBuilder temp = new StringBuilder(500);
            int i = GetPrivateProfileString(Section, IniKey, "", temp, 500, iniFileName);
            return temp.ToString();
        }

        /// <summary>
        /// 读取INI文件(找不到配置文件返回默认值)
        /// </summary>
        /// <param name="Section">段落</param>
        /// <param name="IniKey">关键字</param>
        /// <returns></returns>
        public static string GetFieldValue(string Section, string IniKey,string strDefault,string iniFileName)
        {        
            StringBuilder temp = new StringBuilder(500);
            int i = GetPrivateProfileString(Section, IniKey, strDefault, temp, 500, iniFileName);
            return temp.ToString();
        }

        [DllImport("kernel32")]
        public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        #endregion

        #region 写INI文件
        /// <summary>
        /// 写INI文件
        /// </summary>
        /// <param name="Section">段落</param>
        /// <param name="IniKey">关键字</param>
        /// <returns></returns>
        public static long WriteValue(string Section, string IniKey, string NewValue,string iniFileName)
        {         
            long i = WritePrivateProfileString(Section, IniKey, NewValue, iniFileName);
            return i;
        }

        [DllImport("kernel32")]
        public static extern long WritePrivateProfileString(
            string section, string key, string val, string filePath);
        #endregion
    }
}